package com.lb.lock.service.impl;

import com.lb.lock.aspect.TryAgainException;
import com.lb.lock.common.ApiException;
import com.lb.lock.common.ApiResultEnum;
import com.lb.lock.common.Consts;
import com.lb.lock.mapper.UsrUserAccountMapper;
import com.lb.lock.po.UsrUserAccount;
import com.lb.lock.service.IUserAccountService;
import com.lb.lock.vo.TransferDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserAccountService implements IUserAccountService {


    @Autowired
    private UsrUserAccountMapper usrUserAccountMapper;

    @Override
    public void transfter(TransferDTO dto) throws Exception {
        updateAccount(dto.getFromUserId(),dto.getAmount(), Consts.ACCOUNT_OUT);
        updateAccount(dto.getToUserId(),dto.getAmount(), Consts.ACCOUNT_IN);
    }

    /**
     * 更新账户余额
     * @param userId 账户用户ID
     * @param amount    操作金额数量
     * @param state     转入--1 ，转出 -- 0
     * @throws Exception
     */
    public void updateAccount( Long userId, BigDecimal amount,int state) throws Exception{
        UsrUserAccount userAccount = usrUserAccountMapper.getUserAccountByUserId(userId);
        if(userAccount == null){
            throw new ApiException(ApiResultEnum.ACCOUNT_NOT_FOUND);
        }
        BigDecimal afterBalance = BigDecimal.ZERO;
        if(state == Consts.ACCOUNT_OUT){
            if(userAccount.getBalance().compareTo(amount)<0){
                throw new ApiException(ApiResultEnum.ACCOUNT_NOT_SUFFICIENT);
            }
            afterBalance = userAccount.getBalance().subtract(amount);
        }else if(state == Consts.ACCOUNT_IN){
            afterBalance = userAccount.getBalance().add(amount);
        }
        userAccount.setBalance(afterBalance);
        userAccount.setModifyBy(userId);
        userAccount.setModifyTime(LocalDateTime.now());
        if(!usrUserAccountMapper.updateAccount(userAccount)){
            //如果更新失败就抛出去，重试
            throw new TryAgainException(ApiResultEnum.ERROR_TRY_AGAIN);
        }
    }
}
